import React, { Component } from 'react'
import { Table, Input, Button, Space ,Row,Col} from 'antd';
import Highlighter from 'react-highlight-words';
import { SearchOutlined } from '@ant-design/icons';
import axios from 'axios'
import echarts from 'echarts'
import _ from "lodash"
export default class Order extends Component {
    echartsdata = []
    myChart = null

    echartsdata1 = []
    echartsdata2 = []
    echartsdata2 = []
    myChart1=null
    state = {
        datalist: [],
        searchText: '',
        searchedColumn: '',
        itemlist: ''
    }
    componentDidMount() {
        axios.get("http://localhost:5000/order").then(res => {
            // console.log(res.data)
            this.setState({
                datalist: res.data
            })
            // 数据处理
            this.dataFilter(res.data)
            // 渲染
            this.renderEcharts()
            this.renderEcharts1()
        })


    }
    dataFilter = (data) => {
        // console.log(data)
        let newitem=[]
        data.map(item=>{
            // console.log(item.menu[0])
            return  newitem.push(item.menu[0])
        })
        console.log(newitem)
        let newdata = _.groupBy(data, 'tstate')
        let newdata1 = _.groupBy(newitem, 'tname')
        let newdata2 = _.groupBy(newitem, 'total')
        let newdata3 = _.groupBy(newitem, 'tpric')
        this.echartsdata = newdata
        this.echartsdata1 = newdata1
        this.echartsdata2 = newdata2
        this.echartsdata3 = newdata3
        // console.log(newdata2)
        // console.log(newdata)
        // console.log(this.echartsdata)
    }
    renderEcharts = () => {

        let data1 = []
        for (let item in this.echartsdata) {
            // console.log(item)
            data1.push({
                value: this.echartsdata[item].length,
                name: item
            })
        }
        // console.log(data1)
        var option = {
            backgroundColor: '#2c343c',

            title: {
                text: '订单状态总览表',
                left: 'center',
                top: 20,
                textStyle: {
                    color: '#ccc'
                }
            },

            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
            },

            visualMap: {
                show: false,
                min: 0,
                max: 6,
                inRange: {
                    colorLightness: [0, 1]
                }
            },
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '50%'],
                    data: data1.sort(function (a, b) { return a.value - b.value; }),
                    roseType: 'radius',
                    label: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    },
                    labelLine: {
                        lineStyle: {
                            color: 'rgba(255, 255, 255, 0.3)'
                        },
                        smooth: 0.2,
                        length: 10,
                        length2: 20
                    },
                    itemStyle: {
                        color: '#c23531',
                        shadowBlur: 200,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    },

                    animationType: 'scale',
                    animationEasing: 'elasticOut',
                    animationDelay: function (idx) {
                        return Math.random() * 200;
                    }
                }
            ]
        };
        this.myChart = echarts.init(document.getElementById('main'));
        this.myChart.setOption(option);
        window.onresize = () => {
            // console.log('resize')
            this.myChart && this.myChart.resize()
        }
    }
    renderEcharts1 = () => {

        let data1 = []
        for (let item in this.echartsdata1) {
            // console.log(item)
            data1.push(item)
        }

        let data2 = []//商品的单价
        
        for (let item in this.echartsdata3) {
            // console.log(item)
            data2.push(Number(item))
        }
    //    console.log(data2)
        let data3 = [] //商品的总个数
        Object.values(this.echartsdata2).map(item=>{
            // console.log(item.length) //商品的总个数
            return data3.push(item.length)
        })
        data2.forEach(item=>{
            console.log(item)
        })
        data3.forEach(item=>{
            console.log(item)
        })

        let data4 = [data2[0]*data3[0],data2[1]*data3[1],data2[2]*data3[2],data2[3]*data3[3]]

        
        console.log(data4)
        var option = {
            title: {
                text: '商品收入总览表',
                left: 'center',
                top: 20,
                textStyle: {
                    color: '#ccc'
                }
            },
            xAxis: {
                type: 'category',
                data: data1
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                type:'bar',
                barWidth:50,
                data: data4,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,		//开启显示
                            position: 'top',	//在上方显示
                            textStyle: {	    //数值样式
                                color: 'black',
                                fontSize: 16
                            }
                        }
                    }
                }
            }]
           

        };
        this.myChart1 = echarts.init(document.getElementById('main1'));
        this.myChart1.setOption(option);
        
    }
    render() {
        const columns = [
            {
                title: '订单编号',
                dataIndex: 'id',
                key: 'id',
                ...this.getColumnSearchProps('id'),
            },
            {
                title: '支付方式',
                dataIndex: 'pay',
                key: 'pay'
            },
            {
                title: '送货方式',
                dataIndex: 'mailing',
                key: 'mailing',
                render: text => {
                    // console.log(text)
                    return <div style={{ textAlign: 'center' }}>
                        <span>{text[0].mode}</span><br />
                        <span>{text[1].freight}</span>
                    </div>

                }
            },
            {
                title: '菜单列表',
                dataIndex: 'menu',
                key: 'menu',
                render: text => {
                    const columns = [
                        {
                            title: '名称',
                            dataIndex: 'tname',
                            key: 'tname',
                        },
                        {
                            title: '单价',
                            dataIndex: 'tpric',
                            key: 'tpric',
                        },
                        {
                            title: '数量',
                            dataIndex: 'tnumber',
                            key: 'tnumber',
                        },
                        {
                            title: '合计',
                            dataIndex: 'total',
                            key: 'total',
                        },

                    ]
                    return <Table columns={columns} dataSource={text} pagination={false} bordered style={{ backgroundColor: 'white' }} rowKey={item => item} />
                }
            },
            {
                title: '下单时间',
                dataIndex: 'time',
                key: 'time',

            },
            {
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
            },
            {
                title: '地址',
                dataIndex: 'adds',
                key: 'adds'
            },
            {
                title: '状态',
                dataIndex: 'tstate',
                key: 'tstate',
                ...this.getColumnSearchProps('tstate'),
                render: text => {
                    if (text === "未付款") {
                        return <span style={{ color: 'red' }}>{text}</span>
                    } else if (text === "等待发货") {
                        return <span style={{ color: 'skyblue' }} >{text}</span>
                    } else if (text === "等待收货") {
                        return <span style={{ color: 'orange' }}>{text}</span>
                    } else {
                        return <span style={{ color: 'green' }} >{text}</span>
                    }

                }
            },
            {
                title: '操作',
                key: 'caozuo',
                render: item => <Button type='primary' danger onClick={() => this.handeldel(item)}>删除</Button>
            }
        ];

        return (

            <div>
                <Table columns={columns} dataSource={this.state.datalist} rowKey={item => { return item.id }} pagination={{ pageSize: 4 }} />
                <Row>
                    <Col span={12}><div id="main" style={{ width: '80%', height: '400px' }}></div></Col>
                    <Col span={12}><div id="main1" style={{ width: '100%', height: '400px' }}></div></Col>
                </Row>
                
            </div>

        )
    }
    handeldel = (item) => {

        axios.delete(`http://localhost:5000/order/${item.id}`).then(res => {
            this.setState({
                datalist: this.state.datalist.filter(data => data.id !== item.id)
            })
        })
    }


    getColumnSearchProps = dataIndex => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={node => {
                        this.searchInput = node;
                    }}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{ width: 90 }}
                    >
                        搜索
            </Button>
                    <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                        重置
            </Button>
                </Space>
            </div>
        ),
        filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
        onFilter: (value, record) =>
            record[dataIndex] ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) : '',
        onFilterDropdownVisibleChange: visible => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: text =>
            this.state.searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                    searchWords={[this.state.searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                    text
                ),
    });

    handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        this.setState({
            searchText: selectedKeys[0],
            searchedColumn: dataIndex,
        });
    };

    handleReset = clearFilters => {
        clearFilters();
        this.setState({ searchText: '' });
    }
}
